package com.zjy.business.system.dao;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zjy.business.system.domain.entity.SysRoleMenu;
import com.zjy.business.system.domain.entity.SysUserRole;
import com.zjy.business.system.mapper.SysRoleMenuMapper;
import com.zjy.config.RedisServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yxb
 * create_time: 2024-10-22 14:47
 * description: 
 */
@Service
public class SysRoleMenuDao extends RedisServiceImpl<SysRoleMenuMapper, SysRoleMenu> {

    @Resource
    @Lazy
    private SysUserRoleDao sysUserRoleDao;

    /**
     * 根据用户ID查询该用户可以访问的菜单ID列表
     *
     * @param adminUserId 管理员用户的ID，用于查询该用户的角色和对应的菜单权限
     * @return 返回一个包含用户可访问的菜单ID的列表
     */
    public List<Long> queryMenuIdByUserId(Long adminUserId) {
        List<Long> menuIds = new ArrayList<>();
        sysUserRoleDao.findCacheList(SysUserRole::getUserId, adminUserId).forEach(item -> {
            for (SysRoleMenu roleMenu : findCacheList(SysRoleMenu::getRoleId, item.getRoleId())) {
                menuIds.add(roleMenu.getMenuId());
            }
        });
        return menuIds;
    }

    public void removeByRoleId(Long roleId) {
        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleMenu::getRoleId, roleId);
        this.remove(wrapper);
    }

    /**
     * 检查菜单是否绑定了角色
     * @param menuId 菜单id
     * @return 绑定数量
     */
    public long checkMenuIsBindRole(Long menuId) {
        return this.lambdaQuery()
                .eq(SysRoleMenu::getMenuId, menuId)
                .count();
    }
}
